package course

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/elastic/go-elasticsearch/v7"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"strings"

	"yangming-college/app/speciality/cmd/v1/api/internal/svc"
	"yangming-college/app/speciality/cmd/v1/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteCourseLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteCourseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteCourseLogic {
	return &DeleteCourseLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteCourseLogic) DeleteCourse(uid int64, req *types.CourseId) error {
	// 判断文档是否存在
	exists, err := documentExistsByUIDAndID(uid, req.Id, l.svcCtx.ESClinet)
	if err != nil {
		return err
	}

	if exists {
		// 文档存在，执行删除操作
		// 准备 Delete 请求
		reqDelete := esapi.DeleteRequest{
			Index:      "course",
			DocumentID: req.Id,
		}
		// 执行 Delete 请求
		resDelete, err := reqDelete.Do(context.Background(), l.svcCtx.ESClinet)
		if err != nil {
			return err
		}
		defer resDelete.Body.Close()

		if resDelete.IsError() {
			return errors.New(fmt.Sprintf("Error deleting document: %s", resDelete.String()))
		}

		// 解析 Delete 结果
		var result map[string]interface{}
		if err := json.NewDecoder(resDelete.Body).Decode(&result); err != nil {
			return err
		}

		// 检查是否删除成功
		if result["result"] == "deleted" {
			return nil
		} else {
			return errors.New("Document not deleted")
		}
	}

	// 文档不存在，返回错误
	return errors.New("Document not found")
}

func documentExistsByUIDAndID(uid int64, docID string, clinet *elasticsearch.Client) (bool, error) {
	//todo 删除课程时，删除课程相关的所有章节以及相应的视频

	// 构建查询
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"bool": map[string]interface{}{
				"must": []map[string]interface{}{
					{
						"term": map[string]interface{}{
							"_id": docID,
						},
					},
					{
						"term": map[string]interface{}{
							"uid": uid,
						},
					},
				},
			},
		},
	}

	// 将查询转换为 JSON
	queryJSON, err := json.Marshal(query)
	if err != nil {
		return false, err
	}

	// 准备 Search 请求
	reqSearch := esapi.SearchRequest{
		Index: []string{"course"},
		Body:  strings.NewReader(string(queryJSON)),
	}

	// 执行 Search 请求
	resSearch, err := reqSearch.Do(context.Background(), clinet)
	if err != nil {
		return false, err
	}
	defer resSearch.Body.Close()

	if resSearch.IsError() {
		return false, errors.New(fmt.Sprintf("Error searching document: %s", resSearch.String()))
	}

	// 解析 Search 结果
	var result map[string]interface{}
	if err := json.NewDecoder(resSearch.Body).Decode(&result); err != nil {
		return false, err
	}

	// 判断是否有匹配的文档
	hits, ok := result["hits"].(map[string]interface{})["hits"].([]interface{})
	return ok && len(hits) > 0, nil
}
